package com.zpself.module.多线程.atomic;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author By ZengPeng
 * @Description 被AtomicInteger  其实就是cas  ,线程数量大，并不好用
 * @date in  2021/3/3 19:51
 * @Modified By
 */
public class AtomicInteger实现累加 {
    private static  AtomicInteger  i= new AtomicInteger(0);
    @Test
    public void add() throws  InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        final CountDownLatch readying = new CountDownLatch(1);//线程准备
        final CountDownLatch over = new CountDownLatch(10);//线程跑完了  ，统计耗时

        for (int j = 0; j < 10; j++) {
            executorService.execute(() -> {
                try {
                    readying.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程:"+Thread.currentThread().getName()+"开始工作了！");
                for (int k = 0; k < 100000; k++) {
                    i.getAndIncrement();
                }
                over.countDown();
            });
        }

        System.out.println("---------------准备---------------");

        System.out.println("---------------开始---------------");
        readying.countDown();
        long start = System.currentTimeMillis();

        over.await();
        System.out.println("---------------结束---------------");

        System.out.println("输出i = "+i.get());
        System.out.println("耗时 = "+(System.currentTimeMillis()-start));
    }
}
